//
//  ViewController.mm
//  Checkers2015
//
//  Created by Dmitry Tatarinov on 2/6/15.
//  Copyright (c) 2015 Huly-Gun Soft. All rights reserved.
//
//


#import "stage.h"
#import "mainmenu.h"
#import "game.h"
#import "MoreGamesViewController.h"
#import "MainScreenView.h"
#import "LevelSelectTableViewController.h"
#import "GameScoreViewController.h"
#import "ScoreView.h"
//=========================================

@interface ViewController ()

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self authenticateLocalPlayer];
    _achievementsDictionary = [[NSMutableDictionary alloc] init];
    
    int orientation;
    #if TARGET_IPHONE_SIMULATOR
        orientation = 0;
    #else
        orientation = 0;
    #endif
    
    xGraphics3D(orientation, true, [[UIApplication sharedApplication] keyWindow]);
    //MenuStage *stage = new MenuStage();
    //stage->Load();
    //stage->controller = self;
    curController = self;
    
    animationInterval = 1.0 / 60.0;
    [self startAnimation];
    
    [self setupInterface];
    
    //[[MKStoreKit sharedKit] startProductRequest];
    //[[MKStoreKit sharedKit] availableProducts];
}

//===========================================================================================
#pragma mark setup Interface

- (void)setupInterface
{
    // Main Screen
    CGFloat ofset = 32;
    CGFloat btnWidth = 128.0;
    CGFloat btnHeight = 48.0;
 
    [self loadMainView];

    // Game Pause Screen
    ofset = 24;
    
    _pauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_pauseBtn setTitle:@"Pause" forState:UIControlStateNormal];
    [_pauseBtn setFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
    //_pauseBtn.center = CGPointMake(SCREEN_WIDTH/2, ofset);
    _pauseBtn.center = CGPointMake(SCREEN_WIDTH - btnWidth/2 - ofset, SCREEN_HEIGHT - btnHeight/2 - ofset);
    [_pauseBtn addTarget:self action:@selector(pauseGame) forControlEvents:UIControlEventTouchUpInside];
    [xGetViewController().view addSubview:_pauseBtn];
    
    ofset = 32;
    
    _resumeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_resumeBtn setTitle:@"Resume Game" forState:UIControlStateNormal];
    [_resumeBtn setFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
    _resumeBtn.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2 - ofset);
    [_resumeBtn addTarget:self action:@selector(resumeGame) forControlEvents:UIControlEventTouchUpInside];
    [xGetViewController().view addSubview:_resumeBtn];
    
    _restartGameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_restartGameBtn setTitle:@"Restart Game" forState:UIControlStateNormal];
    [_restartGameBtn setFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
    _restartGameBtn.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    [_restartGameBtn addTarget:self action:@selector(restartGame) forControlEvents:UIControlEventTouchUpInside];
    [xGetViewController().view addSubview:_restartGameBtn];
    
    _backToMenuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backToMenuBtn setTitle:@"Back To Menu" forState:UIControlStateNormal];
    [_backToMenuBtn setFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
    _backToMenuBtn.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2 + ofset);
    [_backToMenuBtn addTarget:self action:@selector(backToMenu) forControlEvents:UIControlEventTouchUpInside];
    [xGetViewController().view addSubview:_backToMenuBtn];
    
    [self showGamePauseBtn:false];
    _pauseBtn.hidden = true;
    
}

- (void)loadMainView
{
    MainScreenView *mainScreenView = [[MainScreenView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andDelegate:self];
    [xGetViewController().view addSubview:mainScreenView];
}

- (void)loadLevelSelect
{
    LevelSelectTableViewController *vc = [[LevelSelectTableViewController alloc] init];
    vc.delegate = self;
    [xGetViewController() presentViewController:vc animated:false completion:nil];
}

- (void)loadGameScore
{
    GameScoreViewController *vc = [[GameScoreViewController alloc] init];
    vc.delegate = self;
    [xGetViewController() presentViewController:vc animated:false completion:nil];
}

- (void)showCurrentScore
{
    ScoreView *curScoreView = [[ScoreView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andDelegate:self];
    [xGetViewController().view addSubview:curScoreView];
}

- (void)showGamePauseBtn: (BOOL) show
{
    if (show)
    {
        _resumeBtn.hidden = false;
        _restartGameBtn.hidden = false;
        _backToMenuBtn.hidden = false;
    }
    else
    {
        _resumeBtn.hidden = true;
        _restartGameBtn.hidden = true;
        _backToMenuBtn.hidden = true;
    }
}

- (void)mainScreenBtnPressed: (id) sender
{
    long tag = [sender tag];
    NSLog(@"tag: %ld",tag );
    
    if (tag < 300)
    {
        [self loadLevelSelect];
        playerMode = (int)tag/100;
    }
    else
    {
        if (tag == 700){
            [self showGameCenter];
        }
        if (tag == 800){
            [self buyInapp];
        }
    }
}

- (void)startGame
{
    //NSLog(@"player: %d / mode: %d", playerMode, gameMode);
    
    _pauseBtn.hidden = false;
    _pauseBtn.enabled = true;
    
    GameStage *stage = new GameStage();
    stage->playerMode = playerMode;
    stage->gameMode = gameMode;
    stage->Load();
}

- (void)pauseGame
{
    [self showGamePauseBtn:true];
    _pauseBtn.enabled = false;
    global_pause = true;
}
- (void)resumeGame
{
    [self showGamePauseBtn:false];
    _pauseBtn.enabled = true;
    global_pause = false;
}

- (void)unloadGame
{
    GameStage *stage = (GameStage *)Stage::GetActive();
    stage->UnloadActive();
    global_pause = false;
}

- (void)restartGame
{
    [self showGamePauseBtn:false];
    _pauseBtn.hidden = false;
    _pauseBtn.enabled = true;
    
    /*
    GameStage *stage = (GameStage *)Stage::GetActive();
    stage->UnloadActive();
    
    stage = new GameStage();
    stage->playerMode = playerMode;
    stage->gameMode = gameMode;
    stage->Load();
    */
    [self unloadGame];
    global_pause = false;
    [self startGame];
}

- (void)backToMenu
{
    [self showGamePauseBtn:false];
    _pauseBtn.hidden = true;
    
    GameStage *stage = (GameStage *)Stage::GetActive();
    stage->UnloadActive();
    
    [self loadLevelSelect];
    
    global_pause = false;
}

- (void)goToGameScore
{
    [self showGamePauseBtn:false];
    _pauseBtn.hidden = true;
    
    [self loadGameScore];
    
    //global_pause = false;
}

- (void)showMoreGames
{
    MoreGamesViewController *vc = [[MoreGamesViewController alloc] init];
    [xGetViewController() presentViewController:vc animated:false completion:nil];
}

//===========================================================================================
#pragma mark Game Center

- (void)authenticateLocalPlayer
{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    
    localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
        if (viewController != nil) {
            [xGetViewController() presentViewController:viewController animated:YES completion:nil];
        }
        else {
            if ([GKLocalPlayer localPlayer].authenticated) {
                NSLog(@"GC enabled");
                //[self showGameCenter];
                //[self showLeaderboardAndAchievements:false];
            }
            else {
                NSLog(@"GC disabled");
            }
        }
    };
}

- (void)showGameCenter
{
    GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc] init];
    
    if (gameCenterController != nil)
    {
        gameCenterController.gameCenterDelegate = self;
        
        [xGetViewController() presentViewController: gameCenterController animated: YES completion:nil];
    }
}

- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
{
    [xGetViewController() dismissViewControllerAnimated:YES completion:nil];
}

- (void)showLeaderboardAndAchievements:(BOOL)shouldShowLeaderboard
{
    GKGameCenterViewController *gcViewController = [[GKGameCenterViewController alloc] init];
    
    gcViewController.gameCenterDelegate = self;
    
    if (shouldShowLeaderboard) {
        gcViewController.viewState = GKGameCenterViewControllerStateLeaderboards;
       // gcViewController.leaderboardIdentifier = leaderboardIdentifier;
    }
    else{
        gcViewController.viewState = GKGameCenterViewControllerStateAchievements;
    }
    
    [xGetViewController() presentViewController:gcViewController animated:YES completion:nil];
}

- (void)reportScore: (int) curScore lbIdentifier: (NSString *)leaderboardIdentifier
{
    GKScore *score = [[GKScore alloc] initWithLeaderboardIdentifier:leaderboardIdentifier];
    score.value = curScore;
    
    [GKScore reportScores:@[score] withCompletionHandler:^(NSError *error) {
        if (error != nil) {
            NSLog(@"%@", [error localizedDescription]);
        }
    }];
}

- (void) reportAchievementIdentifier: (NSString*) identifier percentComplete: (float) percent
{
    GKAchievement *achievement = [self getAchievementForIdentifier:identifier];
    
    if (achievement)
    {
        achievement.percentComplete = percent;
        
        [achievement reportAchievementWithCompletionHandler:^(NSError *error)
        {
             if (error != nil)
             {
                 // Log the error.
             }
         }];
    }
}

- (void) loadAchievements
{
    [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error)
    {
         if (error == nil)
         {
             for (GKAchievement* achievement in achievements)
                 [_achievementsDictionary setObject: achievement forKey: achievement.identifier];
         }
     }];
}

- (GKAchievement*) getAchievementForIdentifier: (NSString*) identifier
{
    GKAchievement *achievement = [_achievementsDictionary objectForKey:identifier];
    
    if (achievement == nil)
    {
        achievement = [[GKAchievement alloc] initWithIdentifier:identifier];
        [_achievementsDictionary setObject:achievement forKey:achievement.identifier];
    }
    
    return achievement;
}

- (void)showBanner
{
    NSString* title = @"Title";
    
    NSString* message = @"Message";
    
    [GKNotificationBanner showBannerWithTitle: title message: message
     
                            completionHandler:^{
                                
                                //[self advanceToNextInterfaceScreen]
                                
                            }];
}

//===========================================================================================
#pragma mark Store Kit

- (void)buyInapp
{
    [self showMoreGames];
}


//===========================================================================================
#pragma mark view main functions

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
   // return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

//
#pragma mark iXors animation and draw

- (void)drawView
{
    if (!global_pause)
    {
        // check stage
        if(Stage::GetActive() == NULL) return;
        // update stage
        Stage::GetActive()->Update();
        // render stage
        Stage::GetActive()->Render();
    }
    else
    {
        xFlushTouches();
        xFlushAcceleration();
        //xCls();
        //xFlip();
    }
}

- (void)layoutSubviews
{
    xResetGraphics();
    [self drawView];
}

- (void)startAnimation
{
   animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES];
}

- (void)stopAnimation
{
    animationTimer = nil;
}


@end
